package com.qp.bookkeeping.business.book.service.impl;

import com.qp.bookkeeping.business.book.mapper.ColumnMapper;
import com.qp.bookkeeping.business.book.model.Bo.QueryColumnBo;
import com.qp.bookkeeping.business.book.model.Do.ColumnDo;
import com.qp.bookkeeping.business.book.model.businessEnum.ColumnLevel;
import com.qp.bookkeeping.business.book.model.businessEnum.YesNoFlag;
import com.qp.bookkeeping.business.book.model.req.QueryColumnReq;
import com.qp.bookkeeping.business.book.model.rsp.QueryColumnRsp;
import com.qp.bookkeeping.business.book.service.ColumnService;
import com.qp.bookkeeping.common.utils.DatabasesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xutianqi
 */
@Service
public class ColumnServiceImpl implements ColumnService {
    @Autowired
    DatabasesUtil databasesUtil;

    @Autowired
    ColumnMapper columnMapper;

    /**
     * 查询栏目
     *
     * @param queryColumnReq 查询栏目req
     */
    @Override
    public QueryColumnRsp queryColumns(QueryColumnReq queryColumnReq) {
        List<ColumnDo> columnDos = columnMapper.selectColumns(queryColumnReq);
        List<ColumnDo> systemColumnDos = columnMapper.selectColumns(QueryColumnReq.builder()
                .isCustomer(YesNoFlag.NO)
                .bookType(queryColumnReq.getBookType())
                .build());
        if (CollectionUtils.isEmpty(columnDos)) {
            columnDos = systemColumnDos;
        } else {
            List<String> columnCodes = columnDos.stream().map(ColumnDo::getColumnCode).collect(Collectors.toList());
            List<ColumnDo> distinctColumns = systemColumnDos.stream()
                    .filter(sysColumn -> !columnCodes.contains(sysColumn.getColumnCode())).collect(Collectors.toList());
            columnDos.addAll(distinctColumns);
        }
        if (CollectionUtils.isEmpty(columnDos)) {
            return null;
        }
        List<ColumnDo> parentColumns = columnDos.stream().filter(column -> ColumnLevel.PARENT == column.getColumnLevel()).collect(Collectors.toList());
        List<QueryColumnBo> queryColumnBos = new ArrayList<>();
        for (ColumnDo parentColumnDo : parentColumns) {
            List<ColumnDo> childColumns = columnDos.stream().filter(columnDo -> StringUtils.equals(columnDo.getParentCode(), parentColumnDo.getColumnCode())).collect(Collectors.toList());
            queryColumnBos.add(QueryColumnBo.builder().parentColumnDo(parentColumnDo).childColumnDos(childColumns).build());
        }

        return QueryColumnRsp.builder().queryColumnBos(queryColumnBos).build();
    }
}
